<template>
  <div class="meter-params-set">
    <ports-status>
      <template v-slot:footer>
        <el-row>
          <el-col :span="5">
            <span class="ports-title">{{ $t('modelConnectStatus') }}：</span>
            <span :class="isModelConnectStatusStyle">{{ isModelConnectText }}</span>
          </el-col>
          <el-col :span="19" class="flex">
            <span class="ports-title">{{ t('meterParamsRead') }}：</span>
            <el-button
              class="load-btn"
              type="primary"
              :disabled="portsStore.portsStatus !== 2"
              @click="handleReadConfig"
            >
              读取配置
            </el-button>
            <el-button
              class="load-btn"
              type="primary"
              :disabled="portsStore.portsStatus !== 2"
              @click="handleWriteConfig"
            >
              写入配置
            </el-button>
            <el-upload
              action=""
              accept=".json,.ini"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleUploadFile"
            >
              <el-button class="load-btn margin-left-xs" type="primary">导入配置</el-button>
            </el-upload>
            <el-button class="load-btn margin-left-xs" type="primary" @click="handleExportParams">
              导出配置
            </el-button>
          </el-col>
        </el-row>
      </template>
    </ports-status>

    <div class="content-box">
      <div class="el-scrollbar-box">
        <el-form class="params-config-box" ref="formRef" :model="form">
          <el-row :gutter="17">
            <el-col :span="8">
              <el-form-item label="背光亮度" prop="backlightBrightness">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.backlightBrightness"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(value, key) in backlightBrightnessList"
                      :key="key"
                      :label="value"
                      :value="+key"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="休眠时间" prop="sleepTime">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.sleepTime"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in sleepTimeList"
                      :key="index"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                  <span class="unit-title">min</span>
                </div>
              </el-form-item>

              <el-form-item label="系统电压" prop="voltage">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.voltage"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                    @change="changeVoltage"
                  >
                    <el-option
                      v-for="(item, index) in dicts_voltage"
                      :key="index"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>

                  <span class="unit-title">V</span>
                </div>
              </el-form-item>

              <el-form-item label="欠压门限" prop="undervoltage">
                <div class="flex align-center">
                  <el-input-number
                    class="ipt-box el-input-number-box"
                    v-model="form.undervoltage"
                    :precision="2"
                    :min="0"
                    :controls="false"
                  />
                  <span class="unit-title">V</span>
                </div>
              </el-form-item>

              <el-form-item label="助力比例" prop="assistPercentage">
                <div class="flex align-center">
                  <el-input
                    class="ipt-box"
                    v-model="form.assistPercentage"
                    oninput="value=value.replace(/[^\d]/g, '')"
                  ></el-input>
                </div>
              </el-form-item>

              <el-form-item label="限流门限" prop="currentlimiting">
                <div class="flex align-center">
                  <el-input
                    class="ipt-box"
                    v-model.number="form.currentlimiting"
                    oninput="value=value.replace(/[^\d]/g, '')"
                  ></el-input>
                  <span class="unit-title">A</span>
                </div>
              </el-form-item>

              <el-form-item label="显示轮径" prop="showWheelsize">
                <div class="flex align-center">
                  <el-input
                    class="ipt-box"
                    v-model="form.showWheelsize"
                    oninput="value=value.replace(/[^\d]/g, '')"
                  ></el-input>
                </div>
              </el-form-item>

              <el-form-item label="车轮宽度" prop="tiresSize">
                <el-input
                  class="ipt-box"
                  v-model="form.tiresSize"
                  oninput="value=value.replace(/[^\d]/g, '')"
                ></el-input>
              </el-form-item>

              <el-form-item label="助力档位数" prop="powerGear">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.powerGear"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in powerGearData"
                      :key="index"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="助力磁钢数" prop="assistStartMagnetNumber">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.assistStartMagnetNumber"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in assistStartMagnetNumberData"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="助力限速门限" prop="assistLimit">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.assistLimit"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in assistLimitData"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                  <span class="unit-title">km/h</span>
                </div>
              </el-form-item>

              <el-form-item label="恢复出厂设置" prop="factoryReset">
                <el-select
                  class="ports-select-box"
                  v-model="form.factoryReset"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="YES" :value="0"></el-option>
                  <el-option label="NO" :value="1"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="定速巡航功能" prop="cruise">
                <el-select
                  class="ports-select-box"
                  v-model="form.cruise"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="YES" :value="0"></el-option>
                  <el-option label="NO" :value="1"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="转把限速" prop="rotateHandleSpeedLimit">
                <el-select
                  class="ports-select-box"
                  v-model="form.rotateHandleSpeedLimit"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="正常" :value="0"></el-option>
                  <el-option label="限速6Km" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="缓启动" prop="slowStart">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.slowStart"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in slowStartData"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="轮径" prop="wheelDiameter">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.wheelDiameter"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                    @change="changeCountPerimeter"
                  >
                    <el-option
                      v-for="(value, key) in wheelDiameterData"
                      :key="key"
                      :label="value"
                      :value="+key"
                    >
                    </el-option>
                  </el-select>
                  <span class="unit-title">inch</span>
                </div>
              </el-form-item>

              <el-form-item label="周长" prop="perimeter">
                <div class="flex align-center">
                  <el-input
                    class="ipt-box"
                    v-model.number="form.perimeter"
                    oninput="value=value.replace(/[^\d]/, '')"
                  ></el-input>
                  <span class="unit-title">mm</span>
                </div>
              </el-form-item>

              <el-form-item label="显示单位" prop="unit">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.unit"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dicts_unit"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="+item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="协议" prop="agreement">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.agreement"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dicts_agreement"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="+item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="电量计算方式" prop="power">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.power"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dicts_power"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="测速磁钢数" prop="speedSteel">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.speedSteel"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in speedSteelData"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="电量变化时间" prop="batteryVoltageChangeTime">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.batteryVoltageChangeTime"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in batteryVoltageChangeTimeData"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                  <span class="unit-title">s</span>
                </div>
              </el-form-item>

              <el-form-item label="速度平滑等级" prop="smoothLevel">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.smoothLevel"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in smoothLevelData"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="总线故障超时" prop="allLineErrTimeOut">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.allLineErrTimeOut"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in allLineErrTimeOutData"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                  <span class="unit-title">s</span>
                </div>
              </el-form-item>

              <el-form-item label="蓝牙" prop="bluetooth">
                <el-select
                  class="ports-select-box"
                  v-model="form.bluetooth"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="YES" :value="1"></el-option>
                  <el-option label="NO" :value="0"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="转把分档" prop="rotateHandle">
                <el-select
                  class="ports-select-box"
                  v-model="form.rotateHandle"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="YES" :value="1"></el-option>
                  <el-option label="NO" :value="0"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="开机密码" prop="turnOnPasswd">
                <el-select
                  class="ports-select-box"
                  v-model="form.turnOnPasswd"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="YES" :value="0"></el-option>
                  <el-option label="NO" :value="1"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="助力正反" prop="assist">
                <el-select
                  class="ports-select-box"
                  v-model="form.assist"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="助力正" :value="0"></el-option>
                  <el-option label="助力反" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="车名" prop="ebikeName">
                <el-select
                  class="ports-select-box"
                  v-model="form.ebikeName"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(value, key) in dicts_ebike"
                    :key="+key"
                    :label="value"
                    :value="+key"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="车型" prop="carModel">
                <el-input class="ipt-box" v-model="form.carModel" maxlength="2"></el-input>
              </el-form-item>

              <el-form-item label="默认档位" prop="defaultGear">
                <el-input
                  class="ipt-box"
                  v-model="form.defaultGear"
                  oninput="value=value.replace(/[^\d.]/g, '')"
                ></el-input>
              </el-form-item>
              <el-form-item label="Logo界面" prop="logo">
                <el-select
                  class="ports-select-box"
                  v-model="form.logo"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dicts_logo"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="开机密码" prop="startupPasswd">
                <el-input
                  class="ipt-box"
                  v-model="form.startupPasswd"
                  oninput="value=value.replace(/[^\d.]/g, '')"
                ></el-input>
              </el-form-item>

              <el-form-item label="高级菜单密码" prop="highMenuPasswd">
                <el-input
                  class="ipt-box"
                  v-model="form.highMenuPasswd"
                  oninput="value=value.replace(/[^\d.]/g, '')"
                ></el-input>
              </el-form-item>

              <el-form-item label="电机功率" prop="motorSys">
                <div class="flex align-center">
                  <el-input
                    class="ipt-box"
                    v-model="form.motorSys"
                    oninput="value=value.replace(/[^\d.]/g, '')"
                  ></el-input>
                  <span class="unit-title">W</span>
                </div>
              </el-form-item>

              <el-form-item label="电池容量" prop="batteryCap">
                <div class="flex align-center">
                  <el-input
                    class="ipt-box"
                    v-model.number="form.batteryCap"
                    oninput="value=value.replace(/[^\d.]/g, '')"
                  ></el-input>
                </div>
              </el-form-item>

              <el-form-item label="高速蜂鸣器" prop="highSpeedBuzzerRemind">
                <div class="flex align-center">
                  <el-input
                    class="ipt-box"
                    v-model="form.highSpeedBuzzerRemind"
                    oninput="value=value.replace(/[^\d.]/g, '')"
                  ></el-input>
                </div>
              </el-form-item>
              <el-form-item label="串口通讯电平" prop="serialLevel">
                <div class="flex align-center">
                  <el-select
                    class="ports-select-box"
                    v-model="form.serialLevel"
                    filterable
                    clearable
                    suffix-icon="CaretBottom"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(value, key) in serialLevelLogData"
                      :key="key"
                      :label="value"
                      :value="+key"
                    >
                    </el-option>
                  </el-select>

                  <span class="unit-title">V</span>
                </div>
              </el-form-item>

              <el-form-item label="推车助力" prop="driveAssist">
                <el-select
                  class="ports-select-box"
                  v-model="form.driveAssist"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="YES" :value="1"></el-option>
                  <el-option label="NO" :value="0"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="蜂鸣器开关" prop="buzzerSwitch">
                <el-select
                  class="ports-select-box"
                  v-model="form.buzzerSwitch"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="YES" :value="0"></el-option>
                  <el-option label="NO" :value="1"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="菜单密码" prop="menuPassword">
                <el-select
                  class="ports-select-box"
                  v-model="form.menuPassword"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                >
                  <el-option label="YES" :value="0"></el-option>
                  <el-option label="NO" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script lang='ts' setup>
import { computed, ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

// 组件
import portsStatus from '@renderer/components/portsStatus.vue'

// pinia
import { usePortsStore } from '@renderer/stores/portsStore'
const portsStore = usePortsStore()

// hook
import { useMessage } from '@renderer/hooks/message'
import { useFilereader } from '@renderer/hooks/fileReader'
import { useCommonTools } from '@renderer/hooks/commonTools'
const commonTools = useCommonTools()
const messageTip = useMessage()
const fileReaderHook = useFilereader()

// 配置文件
let configData = ref({})
let parallelism = {
  rotateHandle: 'rotate_handle', // 转把分档
  rotateHandleSpeedLimit: 'rotate_handle_speed_limit', // 转把限速
  slowStart: 'slow_start', // 缓启动
  speedSteel: 'speed_detect_magnet_number', // 测速磁钢数
  undervoltage: 'low_voltage_threshold', // 欠压门限
  currentlimiting: 'current_limit_threshold', // 限流门限
  assistLimit: 'assist_speed_limit_threshold', // 助力限速门限
  wheelDiameter: 'wheelsize', // 轮径
  batteryVoltageChangeTime: 'battery_voltage_change_time', // 电量变化时间
  allLineErrTimeOut: 'bus_overtime', // 总线故障超时时间
  smoothLevel: 'smooth_level', // 速度平滑等级
  unit: 'display_unit', // 显示单位
  bluetooth: 'has_ble_feature', // 蓝牙
  backlightBrightness: 'backlight_brightness', // 背光亮度
  sleepTime: 'sleep_time', // 休眠时间
  voltage: 'system_voltage', // 系统电压
  powerGear: 'assist_level', // 助力档位数
  assist: 'assist_dir', // 助力正反
  assistStartMagnetNumber: 'assist_start_magnet_number', // 助力开始磁钢数
  assistPercentage: 'assist_percentage', // 助力比例
  perimeter: 'peri_meter', // 周长
  agreement: 'uart_protocol', // 协议
  power: 'electricity_method', // 电量计算方式
  driveAssist: 'push_speed_func', // 推车助力
  defaultGear: 'default_assist', // 默认档位
  logo: 'logo', // Logo界面
  serialLevel: 'uart_level', // 串口通讯电平
  buzzerSwitch: 'beep_switch', // 蜂鸣器开关
  highSpeedBuzzerRemind: 'limit_speed_beep', // 高速蜂鸣器提醒
  cruise: 'cruise_enable_switch', // 定速巡航功能
  startupPasswd: 'power_on_password', // 开机密码
  highMenuPasswd: 'menu_password', // 高级菜单密码
  factoryReset: 'res_factory_set', // 恢复出厂设置
  ebikeName: 'ebike_name', // 车名
  motorSys: 'motor_sys', // 电机功率
  batteryCap: 'battery_cap', // 电池容量
  showWheelsize: 'show_wheelsize', // 显示轮径
  tiresSize: 'tires_size', // 车轮宽度
  carModel: 'car_model', // 车型
  turnOnPasswd: 'power_password_switch', // 开机密码
  menuPassword: 'menu_password_switch' // 菜单密码
}

let form = ref<any>({
  backlightBrightness: '',
  sleepTime: '',
  voltage: '',
  undervoltage: 31.5,
  assistPercentage: '128',
  currentlimiting: 12,
  showWheelsize: '',
  tiresSize: '0',
  powerGear: '',
  assistStartMagnetNumber: '',
  assistLimit: '25',
  factoryReset: '',
  cruise: '',
  rotateHandleSpeedLimit: 0,
  slowStart: '1',
  wheelDiameter: 5,
  perimeter: 0,
  unit: '',
  agreement: '',
  power: '',
  speedSteel: 1,
  batteryVoltageChangeTime: '10',
  smoothLevel: '3',
  allLineErrTimeOut: '10',
  bluetooth: '',
  rotateHandle: 0,
  turnOnPasswd: '',
  assist: 0,
  ebikeName: '',
  carModel: '',
  defaultGear: '',
  logo: '0',
  startupPasswd: '2020',
  highMenuPasswd: '2020',
  motorSys: '',
  batteryCap: 0,
  highSpeedBuzzerRemind: '0',
  serialLevel: 1,
  driveAssist: 1,
  buzzerSwitch: 0,
  menuPassword: 0
})
//   背光亮度
const backlightBrightnessList = {
  1: 1,
  2: 2,
  3: 3,
  4: 4,
  5: 5,
  6: 'AUTO'
}

// 休眠时间
const sleepTimeList = [...Array(11)].map((v, i) => i)
//   助力档位数
const powerGearData = [3, 4, 5, 9]
// 助力开始磁钢数
const assistStartMagnetNumberData = [...Array(63)].map((v, i) => String(i + 2))
// 助力限速门限
const assistLimitData = [...Array(256)].map((v, i) => String(i))
// 缓启动参数
const slowStartData = ['0', '1', '2', '3']
// 测速磁钢数
const speedSteelData = [...Array(16)].map((v, i) => i)
// 电量变化时间
const batteryVoltageChangeTimeData = [...Array(60)].map((v, i) => String(i + 1))
// 速度平滑等级
const smoothLevelData = [...Array(11)].map((v, i) => String(i))
// 总线故障超时时间
const allLineErrTimeOutData = [...Array(251)].map((v, i) => String(i + 5))
// 串口通讯电平
const serialLevelLogData = {
  0: '3.3',
  1: '5'
}
// 轮径
const wheelDiameterData = {
  0: 16,
  1: 18,
  2: 20,
  3: 22,
  4: 24,
  5: 26,
  6: '700C',
  7: 28
}
for (let i = 8; i < 100; i++) {
  wheelDiameterData[i] = i * 0.5
}

const changeCountPerimeter = (wheelDiameter) => {
  let wheelDiameterVal
  if (wheelDiameter === 6) {
    wheelDiameterVal = 27.5
  } else {
    wheelDiameterVal = wheelDiameterData[wheelDiameter]
  }
  form.value.perimeter = parseInt(String(wheelDiameterVal * 25.4 * 3.14))
}

interface labelValueType {
  dictLabel
  dictValue
}
// 仪表电压
let dicts_voltage = ref([])
let dicts_unit = ref<labelValueType[]>([])
let dicts_agreement = ref<labelValueType[]>([])
let dicts_power = ref<labelValueType[]>([])
let dicts_ebike = reactive({})
let dicts_logo = ref<labelValueType[]>([])

// 欠压门限
const changeVoltage = (voltageVal) => {
  let voltage
  switch (voltageVal) {
    case 24:
      voltage = 22
      break
    case 36:
      voltage = 31.5
      break
    case 48:
      voltage = 42
      break
    case 52:
      voltage = 45
      break
    case 60:
      voltage = 54
      break
    case 72:
      voltage = 62
      break
  }
  form.value.undervoltage = voltage
}

// 配置字典
const getConfigDicts = (dictName, currentData) => {
  try {
    commonTools.getDicts(dictName).then((res: any) => {
      res.data.forEach(({ dictLabel, dictValue }) => {
        currentData[dictValue] = dictLabel
      })
    })
  } catch (error: any) {
    throw new Error(error)
  }
}

// 读取配置
const handleReadConfig = async () => {
  clearInterval(timer)
  readParamsCount = 0
  const modelConfigData = await handleReadModelConfig()
  messageTip.success('读取配置成功')
  portsStore.onDataReceived = () => {}
  console.log('modelConfigData', modelConfigData)
  handleGetModleConfig(modelConfigData)
}

// 仪表参数读取
let timer: any = null
let readParamsCount = 0
const handleReadModelConfig = () => {
  return new Promise((resolve, reject) => {
    const CMD_ADDRESS = 0xc2
    let dataArr: any = []
    timer = setInterval(() => {
      readParamsCount++

      if (readParamsCount === 20) {
        readParamsCount = 0
        messageTip.error('读取配置失败')
        clearInterval(timer)
      }
      portsStore.writeMsg(portsStore.cmd3aSum(CMD_ADDRESS, []))
      portsStore.onDataReceived = (dataHex) => {
        if (dataArr[2] === 0xc3 && dataArr.slice(4, 4 + dataArr[3]).length === dataArr[3]) {
          console.log(1111, dataArr.slice(4, 4 + dataArr[3]))
          clearInterval(timer)
          resolve(dataArr.slice(4, 4 + dataArr[3]))
        } else {
          dataArr.push(...dataHex)
        }
      }
    }, 500)
  })
}

const handleGetModleConfig = (configBytesData) => {
  console.log('configBytesData', configBytesData)
  try {
    let model3aConfig = configBytesData

    console.log('model3aConfig', model3aConfig)

    const [
      backlightBrightness, // 背光亮度
      sleepTime, // 休眠时间
      voltage, // 系统电压
      powerGear, // 助力档位数
      assist, // 助力正反
      assistStartMagnetNumber, // 助力开始磁钢数
      assistPercentage, // 助力比例
      rotateHandle, // 转把分档
      rotateHandleSpeedLimit, // 转把限速
      slowStart, // 缓启动
      speedSteel, // 测速磁钢数
      undervoltageH, // 欠压门限High
      undervoltageL, // 欠压门限Low
      currentlimiting, // 限流门限
      assistLimit, // 助力限速门限
      wheelDiameter, // 轮径代码
      batteryVoltageChangeTime, // 电量显示变化时间
      allLineErrTimeOut, // 总线故障超时时间
      smoothLevel, // 速度平滑等级
      unit, // 显示单位
      bluetooth, // 蓝牙
      perimeterH, // 周长H
      perimeterL, // 周长L
      agreement, // 协议
      power, // 电量计算方式
      driveAssist, // 推车助力
      defaultGear, // 默认档位
      logo, // Logo界面
      serialLevel, // 串口通讯电平
      buzzerSwitch, // 蜂鸣器开关
      highSpeedBuzzerRemind, // 高速蜂鸣器开关
      cruise, // 定速巡航功能
      startupPasswdH, // 开机密码H
      startupPasswdL, // 开机密码L
      highMenuPasswdH, // 高级菜单密码H
      highMenuPasswdL, // 高级菜单密码L
      factoryReset, // 恢复出厂设置
      ebikeName, // 车名
      motorSysH, // 电机功率H
      motorSysL, // 电机功率L
      batteryCapH, // 电池容量H
      batteryCapL, // 电池容量L
      showWheelsizeH, // 显示轮径H
      showWheelsizeL, // 显示轮径L
      tiresSize, // 车轮宽度
      carModelH, // 车型H
      carModelL, // 车型L
      turnOnPasswd, // 有无开机密码
      menuPassword // 有无菜单密码
    ] = model3aConfig

    form.value = {
      backlightBrightness: Number(backlightBrightness),
      sleepTime: Number(sleepTime),
      voltage: Number(voltage),
      powerGear: Number(powerGear),
      assist: Number(assist),
      assistStartMagnetNumber: String(assistStartMagnetNumber),
      assistPercentage: String(assistPercentage),
      rotateHandle: Number(rotateHandle),
      rotateHandleSpeedLimit: Number(rotateHandleSpeedLimit),
      slowStart: String(slowStart),
      speedSteel: Number(speedSteel),
      undervoltage: commonTools.combineBytesToDecimal(undervoltageH, undervoltageL) / 1000,
      currentlimiting: Number(currentlimiting),
      assistLimit: String(assistLimit),
      wheelDiameter: Number(wheelDiameter),
      batteryVoltageChangeTime: String(batteryVoltageChangeTime),
      allLineErrTimeOut: String(allLineErrTimeOut),
      smoothLevel: String(smoothLevel),
      unit: Number(unit),
      bluetooth: Number(bluetooth),
      perimeter: commonTools.combineBytesToDecimal(perimeterH, perimeterL),
      agreement: Number(agreement),
      power: String(power),
      driveAssist: Number(driveAssist),
      defaultGear: String(defaultGear),
      logo: String(logo),
      serialLevel: Number(serialLevel),
      buzzerSwitch: Number(buzzerSwitch),
      highSpeedBuzzerRemind: String(highSpeedBuzzerRemind),
      cruise: Number(cruise),
      startupPasswd: commonTools.combineBytesToDecimal(startupPasswdH, startupPasswdL),
      highMenuPasswd: commonTools.combineBytesToDecimal(highMenuPasswdH, highMenuPasswdL),
      factoryReset: Number(factoryReset),
      ebikeName: Number(ebikeName),
      motorSys: commonTools.combineBytesToDecimal(motorSysH, motorSysL),
      batteryCap: commonTools.combineBytesToDecimal(batteryCapH, batteryCapL),
      showWheelsize: commonTools.combineBytesToDecimal(showWheelsizeH, showWheelsizeL),
      tiresSize: String(tiresSize),
      carModel: String.fromCharCode(carModelH) + String.fromCharCode(carModelL),
      turnOnPasswd: turnOnPasswd ?? 0,
      menuPassword: menuPassword ?? 0
    }

    console.log('转化后 configData', configData.value)
  } catch (error) {}
}

// 写入仪表参数
let writeParamsTimer: any = null
const handleWriteConfig = async () => {
  if (portsStore.modelOnlineStatus !== 1) {
    messageTip.warning('请先连接仪表并开机')
    return
  }

  if (!areAllValuesPresent(form.value)) {
    messageTip.warning('仪表配置参数均为必填项')
    return
  }

  const paramsConfigBytes = fileReaderHook.writeConfig(form.value)
  console.log('paramsConfigBytes', paramsConfigBytes)

  portsStore.writeMsg(portsStore.cmd3aSum(0xc0, paramsConfigBytes))
  portsStore.onDataReceived = (dataHex) => {
    console.log('数据 can ', dataHex)
    if (dataHex[2] === 0xc1) {
      if (dataHex[4] !== 0) {
        messageTip.success('配置成功')
      } else {
        messageTip.error('配置失败')
      }
    }
  }
}

// 导入配置
const handleUploadFile = async (file) => {
  try {
    const { name, raw } = file
    const isIniFile = name.lastIndexOf('.ini') !== -1

    if (typeof FileReader === 'undefined') {
      return messageTip.warning('您的浏览器不支持文件读取。')
    }

    if (isIniFile) {
      const iniData = await fileReaderHook.parseIni(raw)
      console.log('iniData', iniData, parallelism)
      let transData = {}
      for (let parentKey in iniData) {
        for (let childKey in parallelism) {
          if (parallelism[childKey] === parentKey) {
            let parVal = iniData[parentKey]
            transData[childKey] = parVal
            // 欠压门限
            if (childKey === 'undervoltage' && parVal !== '') {
              transData[childKey] = (+parVal + 20000) / 1000
            }

            // 系统电压
            if (childKey === 'voltage' && parVal !== '') {
              transData[childKey] = dicts_voltage.value[parVal] || parVal
            }

            // 助力开始磁钢数
            if (childKey === 'assistStartMagnetNumber' && parVal !== '') {
              transData[childKey] = assistStartMagnetNumberData[parVal]
            }

            // 休眠时间
            if (childKey === 'sleepTime' && parVal !== '') {
              transData[childKey] = sleepTimeList[parVal]
            }

            // 助力档位数
            if (childKey === 'powerGear' && parVal !== '') {
              transData[childKey] = powerGearData[parVal]
            }

            // 助力限速门限
            if (childKey === 'assistLimit' && parVal !== '') {
              transData[childKey] = assistLimitData[parVal]
            }

            // 电量变化时间
            if (childKey === 'batteryVoltageChangeTime' && parVal !== '') {
              transData[childKey] = batteryVoltageChangeTimeData[parVal]
            }

            // 总线故障超时时间
            if (childKey === 'allLineErrTimeOut' && parVal !== '') {
              transData[childKey] = allLineErrTimeOutData[parVal]
            }

            const childKeyList = [
              'backlightBrightness',
              'currentlimiting',
              'wheelDiameter',
              'perimeter',
              'unit',
              'agreement',
              'speedSteel',
              'ebikeName',
              'batteryCap',
              'bluetooth',
              'driveAssist',
              'factoryReset',
              'rotateHandle',
              'buzzerSwitch',
              'cruise',
              'turnOnPasswd',
              'menuPassword',
              'rotateHandleSpeedLimit',
              'assist',
              'serialLevel'
            ]
            if (childKeyList.includes(childKey) && parVal !== '') {
              transData[childKey] = +parVal
            }
          }
        }
      }

      console.log('transData', transData)

      form.value = transData
    } else {
      const jsonData = await fileReaderHook.parseJson(raw)

      form.value = jsonData?.instrumentModel ?? jsonData
      console.log('jsonData', jsonData)
      messageTip.success('导入配置成功')
    }
  } catch (error) {
    console.error(error)
  }
}

// 导出配置
const handleExportParams = () => {
  if (!areAllValuesPresent(form.value)) {
    messageTip.warning('仪表配置参数均为必填项')
    return
  }

  const jsonData = JSON.stringify(form.value)
  const blob = new Blob([jsonData], { type: 'application/json' })
  const url = URL.createObjectURL(blob)

  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', `配置文件-${+new Date()}`)
  link.click()
  URL.revokeObjectURL(url)
}

const resetSetFile = () => {
  configData.value = {
    backlightBrightness: '',
    sleepTime: '',
    voltage: '',
    powerGear: '',
    agreement: '',
    assist: '',
    assistStartMagnetNumber: '',
    assistPercentage: '',
    rotateHandle: '',
    rotateHandleSpeedLimit: '',
    slowStart: '',
    speedSteel: '',
    currentlimiting: '',
    undervoltage: '',
    assistLimit: '',
    wheelDiameter: '',
    perimeter: '',
    batteryVoltageChangeTime: '',
    allLineErrTimeOut: '',
    smoothLevel: '',
    unit: '',
    bluetooth: '',
    power: '',
    driveAssist: '',
    defaultGear: '',
    logo: '',
    highSpeedBuzzerRemind: '',
    menuPasswd: '',
    startupPasswd: '',
    highMenuPasswd: '',
    factoryReset: '',
    ebikeName: '',
    motorSys: '',
    batteryCap: '',
    showWheelsize: '',
    tiresSize: '',
    carModel: '',
    turnOnPasswd: '',
    menuPassword: '',
    buzzerSwitch: '',
    cruise: '',
    serialLevel: ''
  }
}

const areAllValuesPresent = (obj) => {
  return Object.values(obj).every((value) => value !== '' && value !== null && value !== undefined)
}

let isModelConnectText = ''
const isModelConnectStatusStyle = computed(() => {
  if (portsStore.modelOnlineStatus === 0) {
    isModelConnectText = t('waitingState')
    return 'wait-status'
  } else {
    isModelConnectText = t('Connected')
    return 'success-status'
  }
})

const getPageData = () => {
  commonTools.getDicts('instrument_voltage').then((res: any) => {
    dicts_voltage.value = res.data.map(({ dictValue }) => +dictValue)
  })

  //仪表单位
  commonTools.getDicts('instrument_unit').then((res: any) => {
    dicts_unit.value = res.data
  })

  //仪表协议
  commonTools.getDicts('instrument_agreement').then((res: any) => {
    dicts_agreement.value = res.data
  })

  //仪表协议
  commonTools.getDicts('instrument_power').then((res: any) => {
    dicts_power.value = res.data
  })

  //仪表LOGO界面
  commonTools.getDicts('instrument_logo').then((res: any) => {
    dicts_logo.value = res.data
  })

  // 车名
  getConfigDicts('instrument_ebike_name', dicts_ebike)
}

getPageData()

watch(
  () => portsStatus.value,
  (val) => {
    if (val !== 2) {
      clearInterval(timer)
      clearInterval(writeParamsTimer)
    }
  },
  {
    immediate: true
  }
)

onUnmounted(() => {
  readParamsCount = 0
  clearInterval(timer)

  clearInterval(writeParamsTimer)
})
</script>
<style lang="scss">
.el-scrollbar-box {
  .is-horizontal {
    display: none !important;
  }

  .params-config-box {
    .el-form-item__label {
      color: #fff;
      width: 100px;
    }
  }
}

.el-input-number-box {
  .el-input__inner {
    text-align: left;
  }
}
</style>
<style lang='scss' scoped>
.meter-params-set {
  display: grid;
  row-gap: $default-box-gap;
  grid-template-rows: auto 1fr;
  height: 100%;

  .load-btn {
    width: 76px;
    height: 27px;
    line-height: 27px;
    background: #2697ff;
    border-radius: 6px;
  }

  .content-box {
    box-sizing: border-box;
    background: $default-bg-color;
    border-radius: $boxRadius;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.el-scrollbar-box {
  .params-config-box {
    .unit-title {
      color: #fff;
      width: 45px;
      margin-left: 7px;
      font-size: 12px;
    }

    .el-select,
    .el-input {
      width: 150px;
    }
  }
}
</style>